package com.vancouver.knows.ui.fragment.citynews;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import com.pangu.bean.PageInfo;
import com.pangu.service.ActionException;
import com.pangu.task.mark.ATaskMark;
import com.pangu.ui.browser.PullListItemBrowser;
import com.pangu.ui.refresh.ARefreshViewController;
import com.pangu.util.DeviceUtil;
import com.pangu.util.StringUtil;
import com.squareup.picasso.Picasso;
import com.vancouver.knows.MainApplication;
import com.vancouver.knows.R;
import com.vancouver.knows.ui.activity.citynews.CityNewsCommentsActivity;
import com.vancouver.knows.ui.activity.citynews.CommentReportActivity;
import com.vancouver.knows.util.AppUtils;
import com.vancouver.knows.business.BusinessModule;
import com.vancouver.knows.business.bean.CommentInfo;
import com.vancouver.knows.business.bean.UserInfo;
import com.vancouver.knows.business.task.mark.FetchCommentsTaskMark;
import com.vancouver.knows.business.task.mark.UserDeleteCommentTaskMark;
import com.vancouver.knows.business.task.mark.UserDeleteUpvoteTaskMark;
import com.vancouver.knows.business.task.mark.UserUpvoteTaskMark;
import com.vancouver.knows.util.CircleTransform;

public class CityNewsCommentsListView extends PullListItemBrowser<MainApplication> {

	private BusinessModule bModule;
	private Context mContext;

	public CityNewsCommentsListView(Context context, ARefreshViewController mController) {
		super(context, mController);
		init(context);
	}

	public CityNewsCommentsListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	private void init(Context context) {
		mContext = context;
		bModule = imContext.getBusinessModule();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
		return false;
	}

	@Override
	protected BaseAdapter createAdapter() {
		return new CommentsAdapter();
	}

	@Override
	protected void setListViewParameters(ListView listView) {
		super.setListViewParameters(listView);
		listView.setDivider(new ColorDrawable(getResources().getColor(R.color.line_color)));
		listView.setDividerHeight(1);
	}

	@Override
	protected void handleLoadNewItems(ATaskMark taskMark) {
		FetchCommentsTaskMark fetchCommentsTaskMark = (FetchCommentsTaskMark) taskMark;
		bModule.getServiceWrapper().fetchComments(this, fetchCommentsTaskMark.getPostId(), AppUtils.getUserId(bModule));
	}

	@Override
	public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
		super.receiveResult(taskMark, exception, trackerResult);

		if ((taskMark instanceof UserUpvoteTaskMark || taskMark instanceof UserDeleteUpvoteTaskMark || taskMark instanceof UserDeleteCommentTaskMark)
				&& taskMark.getTaskStatus() == ATaskMark.HANDLE_OVER) {
			notifyDataSetChanged();
		} else if (taskMark instanceof FetchCommentsTaskMark) {
			if (exception != null && exception.getExCode() == 1) {
				cancelStatusView();
				clearLoadingProgressView();
				taskMark.setTaskStatus(ATaskMark.HANDLE_OVER);

				if (mContext instanceof CityNewsCommentsActivity) {
					((CityNewsCommentsActivity) mContext).setShowCommentInput();
				}
			}
		}

	}

	public class CommentsAdapter extends BaseAdapter {

		private LayoutInflater inflater;

		public CommentsAdapter() {
			inflater = LayoutInflater.from(getContext());
		}

		@Override
		public int getCount() {
			List<CommentInfo> data = bModule.getCacheManager().getCommentInfoMap()
					.get(((FetchCommentsTaskMark) mTaskMark).getPostId());
			if (data == null) {
				return 0;
			}
			return data.size();
		}

		@Override
		public Object getItem(int position) {
			return bModule.getCacheManager().getCommentInfoMap().get(((FetchCommentsTaskMark) mTaskMark).getPostId())
					.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (position == (getCount() - 1)) {
				tryQueryNewItems(true, ATaskMark.TYPE_DEFAULT);
			}

			if (convertView == null) {
				convertView = createItemView(parent);
			}

			CommentInfo commentInfo = (CommentInfo) getItem(position);
			if (commentInfo != null) {
				initItemView(convertView, commentInfo);
			}

			return convertView;
		}

		private View createItemView(ViewGroup parent) {
			View view = inflater.inflate(R.layout.comment_item, parent, false);
			ViewHolder viewHolder = new ViewHolder(view);
			view.setTag(viewHolder);

			return view;
		}

		private void initItemView(View convertView, CommentInfo commentInfo) {
			ViewHolder viewHolder = (ViewHolder) convertView.getTag();
			Picasso.with(imContext).load(commentInfo.getAvatar()).transform(new CircleTransform()).placeholder(R.drawable.no_avatar).centerCrop()
					.resizeDimen(R.dimen.comment_head_size, R.dimen.comment_head_size)
					.into(viewHolder.commentHead);
			viewHolder.commentAuthor.setText(commentInfo.getAuthor());
			viewHolder.commentUpvote.setTag(commentInfo);
			viewHolder.commentUpvote.setText(String.valueOf(commentInfo.getUpvoteCount()));
			if (!StringUtil.isEmptyString(commentInfo.getParentAuthor())) {
				viewHolder.commentContent.setText(AppUtils.replaceColor(commentInfo.getContent(),
						"@" + commentInfo.getParentAuthor(), getContext().getResources().getColor(R.color.orange)));
			} else {
				viewHolder.commentContent.setText(commentInfo.getContent());
			}

			viewHolder.commentTime.setText(AppUtils.getDateStr(getContext(), commentInfo.getDateGmt()));
			if ("Y".equals(commentInfo.getUpvoted())) {
				Drawable drawable = getContext().getResources().getDrawable(R.drawable.icon_like_active);
				drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
				viewHolder.commentUpvote.setCompoundDrawables(drawable, null, null, null);
				viewHolder.commentUpvote.setTextColor(getContext().getResources().getColor(R.color.orange));
			} else {
				Drawable drawable = getContext().getResources().getDrawable(R.drawable.icon_like);
				drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
				viewHolder.commentUpvote.setCompoundDrawables(drawable, null, null, null);
				viewHolder.commentUpvote.setTextColor(getContext().getResources().getColor(R.color.common_font));
			}
			viewHolder.commentAnswer.setTag(commentInfo);
			viewHolder.commentReport.setTag(commentInfo);
			viewHolder.commentDel.setTag(commentInfo);
			UserInfo userInfo = bModule.getCacheManager().getUserInfo();
			String userId = userInfo == null ? "" : userInfo.getUserID();
			if (!StringUtil.isEmptyString(userId) && userId.equals(commentInfo.getUserId())) {
				viewHolder.commentDel.setVisibility(View.VISIBLE);
				viewHolder.commentReport.setVisibility(View.GONE);
			} else {
				viewHolder.commentDel.setVisibility(View.GONE);
				viewHolder.commentReport.setVisibility(View.VISIBLE);
			}
		}

		public class ViewHolder {

			@Bind(R.id.commentTime)
			TextView commentTime;
			@Bind(R.id.commentAuthor)
			TextView commentAuthor;
			@Bind(R.id.commentContent)
			TextView commentContent;
			@Bind(R.id.commentAnswer)
			TextView commentAnswer;
			@Bind(R.id.commentUpvote)
			TextView commentUpvote;
			@Bind(R.id.commentReport)
			TextView commentReport;
			@Bind(R.id.commentDel)
			TextView commentDel;
			@Bind(R.id.commentHead)
			ImageView commentHead;

			public ViewHolder(View view) {
				ButterKnife.bind(this, view);
			}

			@OnClick(R.id.commentUpvote)
			public void onCommentUpvoteClick(View view) {
//				if (!AppUtils.getLoginStatus((Activity) getContext())) {
//					return;
//				}
//
//				UserInfo userInfo = bModule.getCacheManager().getUserInfo();
				UserInfo userInfo = bModule.getCacheManager().getUserInfo();
				String userId = null;
				String auid = null;
				if (userInfo != null) {
					userId = userInfo.getUserID();
				} else {
					auid = imContext.getSharedPrefManager().getAuid();
				}
				CommentInfo commentInfo = (CommentInfo) view.getTag();

				if ("Y".equals(commentInfo.getUpvoted())) {
					UserDeleteUpvoteTaskMark taskMark = bModule.getTaskMarkPool().getUserDeleteUpvoteTaskMark(
							commentInfo.getId(), "comment", ((FetchCommentsTaskMark) mTaskMark).getPostId());
					bModule.getServiceWrapper().userDeleteUpvote(CityNewsCommentsListView.this, taskMark,
							userId, auid, commentInfo.getId(), "comment");

				} else {
					UserUpvoteTaskMark taskMark = bModule.getTaskMarkPool().getUserUpvoteTaskMark(commentInfo.getId(),
							"comment", ((FetchCommentsTaskMark) mTaskMark).getPostId());
					bModule.getServiceWrapper().userUpvote(CityNewsCommentsListView.this, taskMark,
							userId, auid, commentInfo.getId(), "comment");
				}
			}

			@OnClick(R.id.commentAnswer)
			public void onCommentAnswerClick(View view) {
				CommentInfo commentInfo = (CommentInfo) view.getTag();
				((CityNewsCommentsActivity) getContext()).userInsertParentComment(commentInfo);
			}

			@OnClick(R.id.commentReport)
			public void onCommentReportClick(View view) {
				if (AppUtils.getLoginStatus(getContext())) {
					CommentInfo commentInfo = (CommentInfo) view.getTag();
					Intent intent = new Intent(getContext(), CommentReportActivity.class);
					intent.putExtra("target_id", commentInfo.getId());
					((Activity) getContext()).startActivity(intent);
				}
			}

			@OnClick(R.id.commentDel)
			public void onCommentDelClick(View view) {
				CommentInfo commentInfo = (CommentInfo) view.getTag();
				UserDeleteCommentTaskMark taskMark = bModule.getTaskMarkPool().createUserDeleteCommentTaskMark(
						commentInfo.getId(), commentInfo.getPostId());
				UserInfo userInfo = bModule.getCacheManager().getUserInfo();
				if (userInfo == null) {
					return;
				}
				bModule.getServiceWrapper().userDeleteComment(CityNewsCommentsListView.this, taskMark,
						userInfo.getUserID(), commentInfo.getId());
			}
		}
	}

}
